//
//  VedioListViewController.m
//  DMT_VR
//
//  Created by xin on 16/10/18.
//  Copyright © 2016年 Elephant-Parade. All rights reserved.
//

#import "VedioListViewController.h"
#import "VedioListTableViewCell.h"
#import "MJRefresh.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#import "MJExtension.h"
#import "AFAppDotNetAPIClient.h"
#import <ReactiveObjC/ReactiveObjC.h>

#import "VideoDetailViewController.h"
#import "DownloadViewController.h"
#import "VedioModel.h"
#import "UIImageView+YYWebImage.h"
#import "MBProgressHUD.h"
#import "Masonry.h"

@interface VedioListViewController ()
{
    NSInteger page;
    UIButton * reloadButton;
}
@property (weak, nonatomic) IBOutlet UIImageView *startView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *searchButton;
@property (weak, nonatomic) IBOutlet UIButton *downButton;
@property (strong, nonatomic) NSMutableArray * dataSource;

@end

@implementation VedioListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:AFNetworkingReachabilityDidChangeNotification object:nil] subscribeNext:^(NSNotification * notification) {
        NSLog(@"userInfo=%@",notification.userInfo);
        NSInteger status = [notification.userInfo[@"AFNetworkingReachabilityNotificationStatusItem"] integerValue];
        
        //动画结束判断是否有网络
        
        NSLog(@"status=%ld",status);
        
        if(status > 0)
        {
            if (!self.dataSource.count) {
                [self.tableView.mj_header beginRefreshing];
            }
            
        }else{
            //没有网络用户手动刷新
            MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.label.text = @"请检查手机网络设置";
            [hud hideAnimated:YES afterDelay:1.5f];
            
            if (!self.dataSource.count) {
                reloadButton.alpha = 1;
                self.tableView.alpha = 0;
            }
        }
    }];
    
    reloadButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:reloadButton];
    [reloadButton setTitle:@"重新加载" forState:UIControlStateNormal];
    reloadButton.layer.cornerRadius = 5.f;
    reloadButton.layer.borderColor = [UIColor grayColor].CGColor;
    reloadButton.layer.borderWidth = 1.f;
    [reloadButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    reloadButton.backgroundColor = [UIColor clearColor];
    @weakify(self);
    [[reloadButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        [self loadNewData];
    }];
    
    __weak typeof (self) weakself = self;
    
    [reloadButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(weakself.view);
        make.width.equalTo(@100);
        make.height.equalTo(@40);
    }];
    
    reloadButton.alpha = 0;
    
    //启动页
//    _startView.image = [UIImage imageNamed:@"default1"];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        CATransition *animation = [CATransition animation];
        animation.duration = 1;
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        animation.type = @"Fade";//pageCurl Fade
        animation.subtype = kCATransitionFromLeft;
        [_startView.layer addAnimation:animation forKey:nil];
        _startView.image = [UIImage imageNamed:@"default2"];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:1.f animations:^{
                _startView.alpha = 0;
            } completion:^(BOOL finished) {
               
            }];
            
        });
    });
    
    //初始化
    
    self.navigationController.fd_prefersNavigationBarHidden = YES;
    
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    
    
    
    self.searchButton.hidden = YES;
    [[self.searchButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        
    }];
    
    [[self.downButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        DownloadViewController * vc = [self.storyboard instantiateViewControllerWithIdentifier:@"DownloadViewController"];
        [self.navigationController pushViewController:vc animated:YES];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = YES;
    
//    self.navigationController.fd_prefersNavigationBarHidden = YES;
}

- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [[NSMutableArray alloc] init];
    }
    return _dataSource;
}

#pragma mark - load data
- (void)loadNewData
{
    [[AFAppDotNetAPIClient sharedClient] GET:@"vediolist.php" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.tableView.alpha = 1;
        reloadButton.alpha = 0;
        //处理数组
        NSLog(@"=====resData=====");
        
        [self.dataSource removeAllObjects];
        NSArray *userArray = [VedioModel mj_objectArrayWithKeyValuesArray:responseObject];

        [self.dataSource addObjectsFromArray:userArray];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"Error: %@", error);
        
        MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        if (error.code == -1009) {
            hud.label.text = @"请检查手机网络设置";
        }
        else
        {
            hud.label.text = [NSString stringWithFormat:@"请求失败，错误代码%ld",error.code];
        }
        [hud hideAnimated:YES afterDelay:1.5f];
        
    }];
}

- (void)loadMoreData
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView.mj_footer endRefreshing];
         [self.tableView.mj_footer endRefreshingWithNoMoreData];
    });
}

#pragma mark - TableView

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = [UIScreen mainScreen].bounds.size.width /1.5f;
    
    return height;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSource.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *  reuseIdentifier = @"VedioListTableViewCell";
    VedioListTableViewCell *cell = (VedioListTableViewCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[VedioListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    }
    
    VedioModel * model = _dataSource[indexPath.row];

    cell.title_ch.text = model.title_ch;
    cell.title_en.text = model.title_en;
    cell.title_type_time.text = [NSString stringWithFormat:@"#%@ / %@",model.type,model.vediotime];
    
    NSURL * imagePath = [NSURL URLWithString:model.imgurl];
    [cell.backgroundImageView
     setImageWithURL:imagePath
     placeholder:[UIImage imageNamed:@"placeholder"]
     options:YYWebImageOptionSetImageWithFadeAnimation
     completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
         
     }];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideoDetailViewController * vc = [[VideoDetailViewController alloc] init];
    vc.vedioModel = _dataSource[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 屏幕方向
- (BOOL)shouldAutorotate{
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}

#pragma mark - 状态栏
//设置样式
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

//设置是否隐藏
- (BOOL)prefersStatusBarHidden {
    //    [super prefersStatusBarHidden];
    return NO;
}

//设置隐藏动画
- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationNone;
}

@end
